package demo1;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectClassDemo {
//    public static void reflectNewInstance() {
//        Class<?> test = null;
//        try{
//            test = Class.forName("demo1.Student");
//            Student student = (Student) test.newInstance();
//        } catch(ClassNotFoundException e) {
//            e.printStackTrace();
//        } catch (InstantiationException e) {
//            throw new RuntimeException(e);
//        } catch (IllegalAccessException e) {
//            throw new RuntimeException(e);
//        }
//    }
//
//    public static void main(String[] args) {
//        ReflectClassDemo.reflectNewInstance();
//    }

    public static void reflectNewInstall() {
    //1. -->需要使用类路径进行获取
        Class<?> test1 = null;
      try{

//    //2. -->需要使用类名进行获取
//          Class<?> test2 = Student.class;
//
//    //3. -->需要使用类的实例对象获取
//          Student student = new Student();
//          Class<?> test3 = student.getClass();


          test1 = Class.forName("demo1.Student");

        //通过Class对象获取Student类的构造器
          Constructor<?> constructor  = test1.getDeclaredConstructor(String.class, int.class);

        //将修改权限修改为true
          constructor.setAccessible(true);

        //直接传参调用
          Object reflectStudent = constructor.newInstance("reflectTest",404);


          //获取Student实例对象的字段 括号内为字段名
          Field field = test1.getDeclaredField("age");

          //将修改权限修改为true
          field.setAccessible(true);

          //设置该字段内容 括号内为实例对象+修改的值
          field.set(reflectStudent,-1);

          //打印，查看修改
          System.out.println(reflectStudent);

          //通过Class对象获取私有方法 括号呢为方法名+参数链表
          Method method = test1.getDeclaredMethod("methodOther");

          //将修改权限改为true
          method.setAccessible(true);

          //传递执行该方法的实例对象
          method.invoke(reflectStudent);


      } catch(ClassNotFoundException e) {
          e.printStackTrace();
      } catch (NoSuchMethodException e) {
          throw new RuntimeException(e);
      } catch (InvocationTargetException e) {
          throw new RuntimeException(e);
      } catch (InstantiationException e) {
          throw new RuntimeException(e);
      } catch (IllegalAccessException e) {
          throw new RuntimeException(e);
      } catch (NoSuchFieldException e) {
          throw new RuntimeException(e);
      }

    }

    public static void main(String[] args) {
        reflectNewInstall();
    }
}

